<template>
  <div class="desktop-container" :style="`background-image: url(${backgroundImage})`" @click="handleDesktopClick">
    <!-- 桌面图标区 -->
    <div class="desktop-icons">
      <desktop-icon
        v-for="app in featuredApps"
        :key="app.id"
        :app="app"
        :is-selected="selectedDesktopIcons.includes(app.id)"
        @click="selectDesktopIcon(app.id)"
        @dblclick="openApp(app.id)"
        @select="selectDesktopIcon(app.id)"
        @unselect="unselectDesktopIcon(app.id)"
        @remove-from-desktop="removeFromDesktop"
        @uninstall="confirmUninstallApp"
      />
    </div>

    <!-- 应用窗口 -->
    <div class="app-windows">
      <app-window
        v-for="window in openedApps"
        :key="window.id"
        :window="window"
        @activate="activateApp"
        @close="closeApp"
        @minimize="minimizeApp"
        @maximize="maximizeApp"
        @restore="restoreMaximizedApp"
        @update-position="updateWindowPosition"
        @update-size="updateWindowSize"
      />
    </div>

    <!-- 状态栏 -->
    <div class="status-bar">
      <div class="status-left">
        <div class="user-profile" @click="showUserProfile">
          <el-avatar :src="userInfo.avatar" :size="24" />
          <span class="username">{{ userInfo.nickname || '未登录' }}</span>
        </div>
      </div>
      <div class="status-center">
        <div class="running-apps">
          <taskbar-item
            v-for="window in openedApps"
            :key="window.id"
            :window="window"
            @click="handleTaskbarAppClick(window.id)"
          />
        </div>
      </div>
      <div class="status-right">
        <el-button class="status-icon" @click="openAppMarket">
          <el-icon><Shop /></el-icon>
        </el-button>
        <el-button class="status-icon" @click="openSettings">
          <el-icon><Setting /></el-icon>
        </el-button>
        <div class="time-display">{{ currentTime }}</div>
        <el-badge :value="notificationCount" :hidden="notificationCount === 0" class="notification-badge">
          <el-button class="status-icon" @click="showNotifications">
            <el-icon><Bell /></el-icon>
          </el-button>
        </el-badge>
      </div>
    </div>

    <!-- 用户资料弹窗 -->
    <el-dialog
      v-model="userProfileVisible"
      title="用户资料"
      width="400px"
    >
      <div class="user-profile-dialog">
        <el-avatar :src="userInfo.avatar" :size="80" class="profile-avatar" />
        <h3>{{ userInfo.nickname || '未登录' }}</h3>
        <p>{{ userInfo.email || '请先登录' }}</p>
        <div class="profile-actions">
          <template v-if="isLoggedIn">
            <el-button @click="openSettings('user')">编辑资料</el-button>
            <el-button type="danger" @click="userStore.logout">退出登录</el-button>
          </template>
          <el-button v-else type="primary" @click="openLoginModal">登录</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 通知列表弹窗 -->
    <el-dialog
      v-model="notificationsVisible"
      title="通知"
      width="400px"
    >
      <div class="notifications-list">
        <template v-if="notifications.length">
          <div v-for="notification in notifications" :key="notification.id" class="notification-item">
            <el-icon><InfoFilled /></el-icon>
            <div class="notification-content">
              <h4>{{ notification.title }}</h4>
              <p>{{ notification.content }}</p>
              <span class="notification-time">{{ notification.time }}</span>
            </div>
          </div>
        </template>
        <el-empty v-else description="暂无通知" />
      </div>
    </el-dialog>

    <!-- 设置弹窗 -->
    <settings-modal 
      v-model:visible="settingsVisible" 
      :initial-tab="settingsActiveTab"
      @close="settingsVisible = false"
    />

    <!-- 应用市场弹窗 -->
    <app-market-modal
      v-model:visible="appMarketVisible"
      @close="appMarketVisible = false"
    />

    <!-- 登录弹窗 -->
    <login-modal
      v-model:visible="loginModalVisible"
      :register="loginAsRegister"
      @close="loginModalVisible = false"
      @login-success="handleLoginSuccess"
    />

    <!-- 确认卸载应用弹窗 -->
    <el-dialog
      v-model="uninstallDialogVisible"
      title="卸载应用"
      width="400px"
    >
      <div v-if="appToUninstall">
        <p>确定要卸载应用"{{ getAppById(appToUninstall)?.name }}"吗？</p>
        <p class="text-warning">卸载后，应用的相关数据将被清除。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uninstallDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="uninstallApp">确认卸载</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import AppWindow from '@/components/AppWindow.vue'
import DesktopIcon from '@/components/DesktopIcon.vue'
import TaskbarItem from '@/components/TaskbarItem.vue'
import SettingsModal from '@/components/SettingsModal.vue'
import AppMarketModal from '@/components/AppMarketModal.vue'
import LoginModal from '@/components/LoginModal.vue'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { useWallpaperStore } from '@/stores/wallpaper'
import { useMockStore } from '@/stores/mock'
import { Menu, Picture, Close, Bell, Setting, Shop, InfoFilled } from '@element-plus/icons-vue'
import { getFeaturedApps, getAppCategories, getAppsByCategoryId } from '@/api/app'
import type { App, AppCategory } from '@/types/app'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()
const wallpaperStore = useWallpaperStore()
const mockStore = useMockStore()

// 背景图片
const backgroundImage = computed(() => wallpaperStore.currentWallpaper || '/wallpapers/1300373.jpg')

// 开始菜单状态
const startMenuOpen = ref(false)

// 壁纸面板状态
const wallpaperPanelOpen = ref(false)

// 当前时间
const currentTime = ref(getFormattedTime())
const timeInterval = ref<number | null>(null)

// 桌面应用
const featuredApps = ref<App[]>([])

// 应用分类
const appCategories = ref(mockStore.getCategories())

// 获取已打开的应用
const openedApps = computed(() => appStore.openedApps)

// 获取被最小化的应用
const minimizedApps = computed(() => appStore.minimizedApps)

// 获取窗口信息
const getWindowById = (id: string) => appStore.getWindowById(id)

// 根据分类获取应用
const getAppsByCategory = (categoryId: number) => {
  return appsByCategory.value[categoryId] || []
}

// 桌面图标选中状态
const selectedDesktopIcons = ref<number[]>([])

// 桌面图标选中和取消选中
const selectDesktopIcon = (appId: number) => {
  // 如果按住 Ctrl 键，则不清除其他选中项
  if (!event || !(event as MouseEvent).ctrlKey) {
    selectedDesktopIcons.value = [appId]
  } else if (!selectedDesktopIcons.value.includes(appId)) {
    selectedDesktopIcons.value.push(appId)
  }
}

const unselectDesktopIcon = (appId: number) => {
  selectedDesktopIcons.value = selectedDesktopIcons.value.filter(id => id !== appId)
}

// 清除所有选中的图标
const clearSelectedIcons = () => {
  selectedDesktopIcons.value = []
}

// 获取应用信息
const getAppById = (appId: number) => {
  return featuredApps.value.find(app => app.id === appId)
}

// 处理任务栏应用点击
const handleTaskbarAppClick = (windowId: string) => {
  const window = getWindowById(windowId)
  if (!window) return
  
  if (window.isMinimized) {
    appStore.restoreApp(windowId)
  } else if (window.isActive) {
    appStore.minimizeApp(windowId)
  } else {
    appStore.activateApp(windowId)
  }
}

// 切换开始菜单
const toggleStartMenu = (state?: boolean) => {
  if (typeof state === 'boolean') {
    startMenuOpen.value = state
  } else {
    startMenuOpen.value = !startMenuOpen.value
  }
  
  // 关闭壁纸面板
  if (startMenuOpen.value) {
    wallpaperPanelOpen.value = false
  }
}

// 切换壁纸面板
const toggleWallpaperPanel = (state?: boolean) => {
  if (typeof state === 'boolean') {
    wallpaperPanelOpen.value = state
  } else {
    wallpaperPanelOpen.value = !wallpaperPanelOpen.value
  }
  
  // 关闭开始菜单
  if (wallpaperPanelOpen.value) {
    startMenuOpen.value = false
  }
}

// 加载推荐应用
const loadFeaturedApps = async () => {
  try {
    const apps = await getFeaturedApps()
    featuredApps.value = apps.length > 0 ? apps : appStore.desktopApps
  } catch (error) {
    console.error('加载推荐应用失败，使用默认应用', error)
    featuredApps.value = appStore.desktopApps
  }
}

// 加载应用分类和应用
const loadAppCategories = async () => {
  try {
    const categories = await getAppCategories()
    appCategories.value = categories.length > 0 ? categories : appStore.categories
    
    // 加载各分类下的应用
    for (const category of appCategories.value) {
      try {
        const apps = await getAppsByCategoryId(category.id)
        appsByCategory.value[category.id] = apps
      } catch (error) {
        console.error(`加载分类 ${category.id} 下的应用失败`, error)
        // 使用默认应用
        appsByCategory.value[category.id] = appStore.installedApps.filter(app => app.categoryId === category.id)
      }
    }
  } catch (error) {
    console.error('加载应用分类失败，使用默认分类', error)
    appCategories.value = appStore.categories
    
    // 使用默认分类的应用
    for (const category of appCategories.value) {
      appsByCategory.value[category.id] = appStore.installedApps.filter(app => app.categoryId === category.id)
    }
  }
}

// 通知相关状态
const notificationsVisible = ref(false)
const notifications = ref(mockStore.getNotifications())
const notificationCount = computed(() => mockStore.unreadNotificationCount)

// 用户资料弹窗状态
const userProfileVisible = ref(false)
const userInfo = computed(() => userStore.userInfo || {
  avatar: '/avatars/default.png',
  nickname: '访客',
  email: ''
})

// 登录状态
const isLoggedIn = computed(() => !!userStore.token)

// 显示用户资料
const showUserProfile = () => {
  if (isLoggedIn.value) {
    userProfileVisible.value = true
  } else {
    openLoginModal()
  }
}

// 显示通知列表
const showNotifications = () => {
  notificationsVisible.value = true
  mockStore.markAllNotificationsAsRead()
}

// 格式化时间（包含秒数）
function getFormattedTime() {
  const now = new Date()
  return now.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  })
}

// 更新时间
function updateTime() {
  currentTime.value = getFormattedTime()
}

// 跳转到应用市场
const openAppMarket = () => {
  appMarketVisible.value = true
}

// 跳转到登录页面
const openLoginModal = (register = false) => {
  loginAsRegister.value = register
  loginModalVisible.value = true
}

// 登录成功处理
const handleLoginSuccess = () => {
  // 可以在这里添加一些登录成功后的操作
}

// 跳转到设置页面
const openSettings = (tab = 'general') => {
  settingsActiveTab.value = tab
  settingsVisible.value = true
}

// 暴露appStore的方法
const {
  openApp,
  activateApp,
  closeApp,
  minimizeApp,
  maximizeApp,
  restoreMaximizedApp,
  restoreApp,
  updateWindowPosition,
  updateWindowSize
} = appStore

// 点击桌面区域时清除选中的图标
const handleDesktopClick = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  
  // 如果点击的不是桌面图标，则清除所有选中的图标
  if (!target.closest('.desktop-icon')) {
    clearSelectedIcons()
  }
}

// 各种模态框状态
const settingsVisible = ref(false)
const settingsActiveTab = ref('general')
const appMarketVisible = ref(false)
const loginModalVisible = ref(false)
const loginAsRegister = ref(false)

// 处理应用数据加载
onMounted(async () => {
  // 初始化壁纸
  if (typeof wallpaperStore.initWallpapers === 'function') {
    await wallpaperStore.initWallpapers()
  }
  
  // 确保应用数据已初始化
  await appStore.initAppData()
  
  // 加载桌面数据
  loadFeaturedApps()
  loadAppCategories()
  
  // 设置时间更新
  timeInterval.value = window.setInterval(updateTime, 1000)
  
  // 添加桌面点击事件
  document.addEventListener('click', handleDesktopClick)
})

onUnmounted(() => {
  if (timeInterval.value) {
    clearInterval(timeInterval.value)
  }
  
  document.removeEventListener('click', handleDesktopClick)
})
</script>

<style scoped>
.desktop-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: cover;
  background-position: center;
  overflow: hidden;
  user-select: none;
}

.desktop-icons {
  display: grid;
  grid-template-columns: repeat(auto-fill, 80px);
  grid-gap: 20px;
  padding: 20px;
  margin-top: 36px;
}

.desktop-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
  padding: 5px;
  border-radius: 5px;
}

.desktop-icon:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.icon-wrapper {
  width: 50px;
  height: 50px;
  margin-bottom: 8px;
}

.app-icon {
  width: 100%;
  height: 100%;
}

.icon-title {
  font-size: 12px;
  color: white;
  text-align: center;
  text-shadow: 0 0 3px rgba(0, 0, 0, 0.8);
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 36px;
  background-color: rgba(42, 42, 42, 0.8);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  padding: 0 10px;
  z-index: 9999;
  color: white;
}

.status-left {
  display: flex;
  align-items: center;
  min-width: 200px;
}

.status-center {
  flex: 1;
  display: flex;
  justify-content: center;
  overflow: hidden;
}

.status-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 0 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-profile:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  font-size: 13px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-icon {
  padding: 4px;
  color: white;
  background: transparent;
  border: none;
}

.status-icon:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.time-display {
  font-size: 13px;
  padding: 0 12px;
}

.notification-badge :deep(.el-badge__content) {
  z-index: 10000;
}

.running-apps {
  display: flex;
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  height: 100%;
}

.taskbar-app {
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 100%;
  border-bottom: 3px solid transparent;
  cursor: pointer;
  transition: all 0.3s;
  color: white;
  margin-right: 2px;
}

.taskbar-app.active {
  background-color: rgba(255, 255, 255, 0.2);
  border-bottom-color: var(--el-color-primary);
}

.taskbar-app.minimized {
  opacity: 0.7;
}

.taskbar-app:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.taskbar-app span {
  margin-left: 5px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-profile-dialog {
  text-align: center;
  padding: 20px 0;
}

.profile-avatar {
  margin-bottom: 16px;
}

.profile-actions {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  gap: 16px;
}

.notifications-list {
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-content {
  flex: 1;
}

.notification-content h4 {
  margin: 0 0 4px;
  font-size: 14px;
}

.notification-content p {
  margin: 0;
  font-size: 13px;
  color: #666;
}

.notification-time {
  font-size: 12px;
  color: #999;
  display: block;
  margin-top: 4px;
}
</style> 